import { create } from 'zustand'

export interface ModelItem {
  id: string
  modelPath: string
  originalPath: string
  name: string
}

interface ModelState {
  models: ModelItem[]
  isLoading: boolean
  error: string | null
}

interface ModelStore extends ModelState {
  addModel: (path: string, originalPath: string) => void
  removeModel: (id: string) => void
  clearModels: () => void
  setLoading: (isLoading: boolean) => void
  setError: (error: string | null) => void
}

function extractFileName(path: string): string {
  const parts = path.replace(/\\/g, '/').split('/')
  return parts[parts.length - 1] || '未命名模型'
}

function generateModelId(): string {
  return `model-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`
}

export const useModelStore = create<ModelStore>((set) => ({
  models: [],
  isLoading: false,
  error: null,

  addModel: (path, originalPath) => {
    set((state) => {
      const exists = state.models.some((m) => m.originalPath === originalPath || m.modelPath === path)
      if (exists) return state

      const newModel: ModelItem = {
        id: generateModelId(),
        modelPath: path,
        originalPath,
        name: extractFileName(originalPath),
      }

      return {
        ...state,
        models: [...state.models, newModel],
        error: null,
      }
    })
  },

  removeModel: (id) => {
    set((state) => ({
      ...state,
      models: state.models.filter((model) => model.id !== id),
    }))
  },

  clearModels: () => {
    set({
      models: [],
      isLoading: false,
      error: null,
    })
  },

  setLoading: (isLoading) => {
    set((state) => ({ ...state, isLoading }))
  },

  setError: (error) => {
    set((state) => ({ ...state, error, isLoading: false }))
  },
}))

